import { getChannelStore, getGoodsCategoryInfo, listCompeteStores, getSales } from './api';
import { TOP_CHANNELS } from '@/constants/index';
import { message, formatDate } from '@/utils/util';

export default {
  name: 'goods-detail-modal',
  props: {
    visible: {
      type: Boolean,
      default: true,
    },
    goods: {
      type: Object,
      default: {},
    },
    topChannelList: {
      type: Array,
      default: () => [],
    },
    resultChannel: {
      type: Array,
      default: () => [],
    },
    competeStoreNames: {
      type: Array,
      default: () => [],
    },
    modal: {
      type: Boolean,
      default: () => true,
    },
    modalAppendToBody: {
      type: Boolean,
      default: () => true,
    },
    appendToBody: {
      type: Boolean,
      default: () => false,
    },
  },

  data() {
    return {
      tabsName: 'base',
      labelWidth: '110px',
      labelWidth2: '130px',
      chartLine: null,
      channelStore: {}, //门店信息
      goodsInfo: {}, //药品信息
      competeStores: [], //竞对门店
      salesInfo: {
        adjustPriceList: [],
        goodsSalesInfo: {},
        isNull: true,
      }, //商品销售信息
    };
  },
  watch: {
    async visible(value) {
      //对话框打开初始化数据
      if (value) {
        this.tabsName = 'base';
        await this.getChannelStore(this.goods.channelCode);
        await this.getGoodsCategoryInfo(this.goods.goodsCode);
        const item = TOP_CHANNELS.find(item => {
          if (this.goods.channelCode.indexOf(item.id) !== -1) {
            return item;
          }
        });
        //蜂窝编码
        const cellularCode = this.goods.cellularCode;
        if (cellularCode) {
          if (this.competeStoreNames && this.competeStoreNames.length > 0) {
            this.listCompeteStores(item.id, this.competeStoreNames, [this.goods.goodsCode]);
          }
        }
      } else {
        this.channelStore = {};
        this.goodsInfo = {};
        this.competeStores = [];
        this.salesInfo = {
          adjustPriceList: [],
          goodsSalesInfo: {},
          isNull: true,
        };
      }
    },
  },
  methods: {
    //获取门店设置
    async getChannelStore(channelCode) {
      if (!channelCode) {
        return;
      }
      try {
        const result = await getChannelStore(channelCode);
        if (result) {
          this.channelStore = {
            ...result,
            topChannelName: TOP_CHANNELS.find(i => i.id === result.topChannelCode)?.name,
            cellularName: this.goods.cellularName,
          };
        }
      } catch (e) {
        message('错误', '获取门店信息异常', 'error');
      }
    },
    //获取药品信息
    async getGoodsCategoryInfo(goodsCode) {
      try {
        this.goodsInfo = await getGoodsCategoryInfo(goodsCode);
      } catch (e) {
        message('错误', '获取药品信息异常', 'error');
      }
    },
    //获取竞对门店
    async listCompeteStores(topChannelCode, storeName, goodsCode) {
      if (!topChannelCode || !storeName || !goodsCode) {
        message('错误', '参数异常', 'error');
        return;
      }
      try {
        this.competeStores = await listCompeteStores(topChannelCode, storeName, goodsCode);
      } catch (e) {
        message('错误', '获取竞对门店异常', 'error');
      }
    },

    async getSales() {
      if (!this.salesInfo.isNull) {
        return;
      }
      try {
        const result = await getSales(this.goods.channelCode, this.goods.goodsCode);
        const { adjustPriceList, goodsSalesInfo } = result || {};
        this.salesInfo = {
          adjustPriceList: adjustPriceList || [],
          goodsSalesInfo: goodsSalesInfo || {},
          isNull: false,
        };
      } catch (e) {
        message('错误', '获取商品销售信息异常', 'error');
      }
    },
    onClose() {
      this.$emit('close');
    },
    handleClick(value) {
      if (value.name === 'sale') {
        this.getSales();
        // this.$nextTick(() => {
        //   this.initChartLineBox();
        // });
      }
    },
    getLimitNum(row, index) {
      //当前限购数
      let limitNum = 0;
      //上次限购数
      let lastLimitNum = 0;
      limitNum = row.limitNum;
      const adjustPrice = this.salesInfo.adjustPriceList[index + 1];
      if (adjustPrice) {
        lastLimitNum = adjustPrice.limitNum;
      }
      if (limitNum && lastLimitNum) {
        return lastLimitNum + '/' + limitNum;
      }
      if (!limitNum && !lastLimitNum) {
        return '无';
      }
      return (lastLimitNum === 0 ? '无' : lastLimitNum) + '/' + (limitNum === 0 ? '无' : limitNum);
    },

    getActivityPriceLimit(row, index) {
      //当前特价限购数
      let activityPriceLimit = 0;
      //上次特价限购数
      let lastActivityPriceLimit = 0;
      activityPriceLimit = row.activityPriceLimit;
      const adjustPrice = this.salesInfo.adjustPriceList[index + 1];
      if (adjustPrice) {
        lastActivityPriceLimit = adjustPrice.activityPriceLimit;
      }
      if (activityPriceLimit && lastActivityPriceLimit) {
        return lastActivityPriceLimit + '/' + activityPriceLimit;
      }
      if (!activityPriceLimit && !lastActivityPriceLimit) {
        return '无';
      }
      return (lastActivityPriceLimit === 0 ? '无' : lastActivityPriceLimit) + '/' + (activityPriceLimit === 0 ? '无' : activityPriceLimit);
    },

    formatDate(time) {
      if (!time) {
        return;
      }
      return formatDate(new Date(time), 'yyyy-MM-dd hh:mm:ss');
    },
    //初始化趋势图
    initChartLineBox() {
      let charts = require('echarts');
      this.chartLine = charts.init(document.getElementById('chartLineBox'), 'canvas', { width: 750, height: 400 });
      // 指定图表的配置项和数据
      let option = {
        tooltip: {
          //设置tip提示
          trigger: 'axis',
        },

        legend: {
          //设置区分（哪条线属于什么）
          data: ['原价', '特价', '销量', '毛利额'],
        },
        color: ['#8AE09F', '#1E90FF', '#FA6F53', '#FFD700'], //设置区分（每条线是什么颜色，和 legend 一一对应）
        xAxis: {
          //设置x轴
          type: 'category',
          boundaryGap: false, //坐标轴两边不留白
          data: ['2019-1-1', '2019-2-1', '2019-3-1', '2019-4-1', '2019-5-1', '2019-6-1', '2019-7-1'],
          name: 'DATE', //X轴 name
          nameTextStyle: {
            //坐标轴名称的文字样式
            color: '#FA6F53',
            fontSize: 14,
            padding: [0, 0, 0, 20],
          },
          axisLine: {
            //坐标轴轴线相关设置。
            lineStyle: {
              color: '#FA6F53',
            },
          },
        },
        yAxis: {
          name: 'SALES VOLUME',
          nameTextStyle: {
            color: '#FA6F53',
            fontSize: 14,
            padding: [0, 0, 10, 0],
          },
          axisLine: {
            lineStyle: {
              color: '#FA6F53',
            },
          },
          type: 'value',
        },
        series: [
          {
            name: '原价',
            data: [220, 232, 201, 234, 290, 230, 420],
            type: 'line', // 类型为折线图
            lineStyle: {
              // 线条样式 => 必须使用normal属性
              normal: {
                color: '#8AE09F',
              },
            },
          },
          {
            name: '特价',
            data: [120, 200, 150, 80, 70, 110, 130],
            type: 'line',
            lineStyle: {
              normal: {
                color: '#1E90FF',
              },
            },
          },
          {
            name: '销量',
            data: [2, 4, 2, 5, 5, 6, 1],
            type: 'line',
            lineStyle: {
              normal: {
                color: '#FA6F53',
              },
            },
          },
          {
            name: '毛利额',
            data: [10, 20, 15, 8, 7, 11, 13],
            type: 'line',
            lineStyle: {
              normal: {
                color: '#FFD700',
              },
            },
          },
        ],
      };

      // 使用刚指定的配置项和数据显示图表。
      this.chartLine.setOption(option);
    },
  },
  mounted() {},
};
